import { takeLatest } from 'redux-saga';
import { put, select, fork } from 'redux-saga/effects';
import { get, REQUEST_POSTLIST, REQUEST_DETAIL, REQUEST_POSTCOMMENT } from '../service/mz.data.service';
import { datefmt } from '../utils/utils';
import _ from 'lodash';
import immutable from 'seamless-immutable';

const pageSizeConst = 15;

function* fetchPostList(action) {
	const data = yield get(REQUEST_POSTLIST, { ...action.payload, pageSize: pageSizeConst });
	let list = yield select(x => x['post']['list']);
	let end = false;
	if (data) {
		if (data.list) {
			let newList = list;
			_.each(data.list, (item) => {
				item.add_time = datefmt(new Date(item.add_time*1000), ("yyyy-MM-dd"))
			});
			if (action.payload.pageNum === 0) {
				list = data.list;
			} else {
				list = list.concat(immutable(data.list));
			}
			end = data.list.length < pageSizeConst;
		}
		yield put({ type: 'post/fetchPostSuccess', payload: { list: list, pageNum: action.payload.pageNum, end: end } });
	}
}

function* initPostDetail(action) {
	yield fork(fetchPostDetail, action);
	yield fork(fetchPostComments, { payload: { id: action.payload.id, pageNum: 0 } });
}

function* fetchPostDetail(action) {
	const data = yield get(REQUEST_DETAIL, action.payload);
	if (data && data.info) {
		data.info.add_time = datefmt(new Date(data.info.add_time*1000), ("yyyy-MM-dd"))
		yield put({ type: 'post/fetchPostSuccess', payload: { info: data.info } })
	}
}

function* fetchPostComments(action) {
	const data = yield get(REQUEST_POSTCOMMENT, { ...action.payload, pageSize: pageSizeConst });
	let list = yield select(x => x['post']['comments']);
	let end = false;
	if (data && data.list) {
		if (data.list) {
			let newList = list;
			_.each(data.list, (item) => {
				item.add_time = datefmt(new Date(item.add_time*1000), ("MM-dd hh:mm"));
				if (item.replies) {
					_.each(item.replies, (replyItem) => {
						replyItem.add_time = datefmt(new Date(replyItem.add_time*1000), ("MM-dd hh:mm"));
					})
				}
			});
			if (action.payload.pageNum === 0) {
				list = data.list;
			} else {
				list = list.concat(immutable(data.list));
			}
			end = data.list.length < pageSizeConst;
		}
		yield put({ type: 'post/fetchPostSuccess', payload: { comments: list, commentPageNum: action.payload.pageNum, commentEnd: end } });
	}
}

export const postSagas = function* () {
	yield takeLatest('post/fetchPostList', fetchPostList);
	yield takeLatest('post/initPostDetail', initPostDetail);
	yield takeLatest('post/fetchComments', fetchPostComments);
}
